package com.pers.springcloud;

import cn.hutool.crypto.digest.MD5;
import cn.hutool.http.HttpRequest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author: 黄建
 * @Date: 2020/3/7 14:46
 */
@SpringBootApplication
//开启服务注册中心
@EnableEurekaServer
@RestController
public class EurekaMain7001 {

    String PRIVATE_KEY = "2b0c232876412843b7e8e9f200cf64e3";
    String URL = "url";

    @GetMapping("/getAddress")
    public ResponseEntity<String> getGodAddress(HttpServletRequest request){
        Map<String, String[]> parameterMap = request.getParameterMap();
        //排序
        List<String> sortParams = parameterMap.keySet().stream().sorted().collect(Collectors.toList());
        //请求地址与请求参数
        StringBuilder requestUrl = new StringBuilder();
        StringBuilder paramsStr = new StringBuilder();
        //处理参数
        for (String key : sortParams) {
            String[] paramArray = parameterMap.get(key);
            if (Objects.nonNull(paramArray) && paramArray.length > 0) {
                //设置url
                if (key.equals(URL)) {
                    requestUrl.append(paramArray[0]);
                    continue;
                }
                //拼接参数
                if (paramsStr.length() > 0) {
                    paramsStr.append("&");
                }
                paramsStr.append(key).append("=").append(paramArray[0]);
            }
        }
        //处理请求request
        String sig = MD5.create().digestHex(paramsStr + PRIVATE_KEY);
        requestUrl.append("?").append(paramsStr.append("&sig=").append(sig));
        return ResponseEntity.ok().body(HttpRequest.get(requestUrl.toString()).execute().body());
    }

    public static void main(String[] args) {
        SpringApplication.run(EurekaMain7001.class,args);
    }
}
